package org.rails.core.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayUtil {
	
	public static String join(List<? extends Object> array,String sep){
		final StringBuffer sbf = new StringBuffer();
		
		for (int i = 0; i < array.size();i++) {
			Object obj = array.get(i);
			if(obj instanceof Number || obj instanceof Boolean)
				sbf.append(obj.toString());
			else 
				sbf.append(obj);
			
			if(i < array.size()-1)
				sbf.append(sep);
			
		}		
		return sbf.toString();
	}
	
	public static String ins(List<? extends Object> array){
		final StringBuffer sbf = new StringBuffer();
		for (int i = 0; i < array.size();i++) {
			Object obj = array.get(i);
			if(obj instanceof Number || obj instanceof Boolean)
				sbf.append(obj.toString());
			else 
				sbf.append("'" + obj.toString().replaceAll("\'","\\\\\'") + "'");
			
			if(i < array.size()-1)
				sbf.append(",");
		}		
		return sbf.toString();
	}
	
	public static Object at(List<? extends Object> array,int index){
		try{
			if(index >= 0){
				return array.get(index);
			}else{
				return array.get(array.size() + index);
			}
		}catch(ArrayIndexOutOfBoundsException e){
			return null;
		}
	}
	
	public static Object first(List<? extends Object> array){
		try{
			return array.get(0);
		}catch(ArrayIndexOutOfBoundsException e){
			return null;
		}
	}
	
	public static Object last(List<? extends Object> array){
		try{
			return array.get(array.size()-1);
		}catch(ArrayIndexOutOfBoundsException e){
			return null;
		}
	}
	
	public static List<? extends Object> uniq(List<? extends Object> array){
		final List<Object> list = new ArrayList<Object>();
		for (Object obj : array) {
			if(!list.contains(obj))
				list.add(obj);
		}
		return list;
	}
	
	public static List<? extends Object> sort(List<? extends Object> array){
		final Object[] os = array.toArray();
		Arrays.sort(os);
		return Arrays.asList(os);
	}
	
	public static List<? extends Object> reverse(List<? extends Object> array){
		final List<Object>  list = new ArrayList<Object>();
		for (Object obj : array) {
			list.add(0, obj);
		}
		return list;
	}

}
